<script setup lang="ts">
import { useConfigTableStore } from '@/stores/config/configTableStore';
import { ViewHelper } from '@/utils/viewHelper';
import { ref, watch } from 'vue';

const props = defineProps({
    modelValue: Boolean,
    tableId: {
        type: Number,
        required: true
    }
});

const emit = defineEmits(['update:modelValue', 'confirm']);

const tableStore = useConfigTableStore();
const selectedId = ref(0);

const handleCurrentChange = (row: any) => {
    selectedId.value = row?.id || 0;
};

const onConfirm = () => {
    emit('confirm', selectedId.value);
    emit('update:modelValue', false);
};

watch(() => props.modelValue, (newVal) => {
    if (!newVal) {
        selectedId.value = 0;
    }
});
</script>

<template>
    <el-dialog
        :model-value="modelValue"
        @update:modelValue="(val: any) => emit('update:modelValue', val)"
        title="选择表格元素"
        width="70%">
        <el-table
            :data="tableStore.getTable(tableId)?.rows"
            highlight-current-row
            @current-change="handleCurrentChange">
            <el-table-column label="ID" prop="id" width="80" />
            <el-table-column 
                v-for="(header, index) in tableStore.getTableHeader(tableId)"
                :key="index"
                :label="header.label">
                <template #default="{ row }">
                    {{ ViewHelper.getTableElementText(header, row.values[index]) }}
                </template>
            </el-table-column>
        </el-table>
        <template #footer>
            <el-button @click="emit('update:modelValue', false)">取消</el-button>
            <el-button type="primary" @click="onConfirm">确定</el-button>
        </template>
    </el-dialog>
</template>

<style scoped>
.el-table {
    margin: 15px 0;
}
</style>